#include "EnemyGroup.h"

//Destructor
cEnemyGroup::~cEnemyGroup(void)
{
  //Remove the enemies
  for (cEnemyListIt lcIt = mEnemies.begin(); lcIt != mEnemies.end(); lcIt++)
  {
    delete (*lcIt);
  }
  mEnemies.clear();
}

//Add enemy to the group of enemies
void cEnemyGroup::AddEnemy(cEnemy *loEnemy)
{
  mEnemies.push_back(loEnemy);
}

 
//Remove an enemy from the group of enemies and delete the object
void cEnemyGroup::RemoveEnemy(cEnemy *loEnemy)
{
  mEnemies.remove(loEnemy);
  delete loEnemy;
}

//Upgrade the position of the group of enemies
void cEnemyGroup::Update(float lfTimeStep)
{
  //Check if the enemies are in the Earth
  if (muiMaxY == 23)
    return;

   //To control the speed of the enemy he can only be moved every 075 ms
  mfElapsedTime += lfTimeStep;
  mfElapsedTimeDown += lfTimeStep;
  if (mfElapsedTime < mfLateralSpeed) return;

  //Caculate the limits of the enemy group
  CalculateLimitEnemies();

  //If touch the left wall change direction
  if ((muiMinX == 0) || (muiMaxX == 79))
    miMoveDirection *= -1;

  //Draw every enemy
  for (cEnemyListIt lcIt = mEnemies.begin(); lcIt != mEnemies.end(); lcIt++)
  {
    //Update X positions
    (*lcIt)->SetX((*lcIt)->GetX() + miMoveDirection);
    
    //Update Y positions 
    if (mfElapsedTimeDown >5.5)
      (*lcIt)->SetY((*lcIt)->GetY() + 1);
  
    //And call enemy update
    (*lcIt)->Update(lfTimeStep);
  }

  mfElapsedTime = 0;

  if (mfElapsedTimeDown < 5.5) return;

  //Update the time counter and the lateral speed
  mfLateralSpeed -= 0.05;
  mfElapsedTimeDown = 0;
}

//Render the group of enemies
void cEnemyGroup::Render()
{
  //Draw every enemy
  for (cEnemyListIt lcIt = mEnemies.begin(); lcIt != mEnemies.end(); lcIt++)
  {
    (*lcIt)->Render();
  }
}


//Method to update the limits of the enemy group
void cEnemyGroup::CalculateLimitEnemies() 
{
  muiMinX = 80;
  muiMaxX = 0;
  muiMinY = 25;
  muiMaxY = 0;

  //Iterate thtrought all the Objects
  for (cEnemyListIt lcIt = mEnemies.begin(); lcIt != mEnemies.end(); lcIt++)
  {
    //Only if its an enemy and has a lower position
    if ((*lcIt)->GetX() < muiMinX)
      muiMinX = (*lcIt)->GetX();
    if ((*lcIt)->GetX() > muiMaxX)
      muiMaxX = (*lcIt)->GetX();
    if ((*lcIt)->GetY() < muiMinY)
      muiMinY = (*lcIt)->GetY();
    if ((*lcIt)->GetY() > muiMaxY)
      muiMaxY = (*lcIt)->GetY();

  }

}

